package controller;

import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description: 删除博客操作
 */
@WebServlet("/blogDelete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 确认登陆
        HttpSession session = req.getSession(false);
        if(session == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录，不能删除!");
            return;
        }
        User user = (User)session.getAttribute("user");
        if(user == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录，不能删除!");
            return;
        }

        // 2. 获取删除的博客bolgId
        String para = req.getParameter("blogId");
        if(para == null || "".equals(para)) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("blogId 参数不正确!");
            return;
        }

        int blogId = Integer.parseInt(para);
        // 3. 查询博客是否存在
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectBlog(blogId);
        if(blog == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("要删除的博客不存在!");
            return;
        }

        // 再次校验，当前的用户是否就是博客的作者
        if(blog.getUserId() != user.getUserId()) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("无权限删除该博客!");
            return;
        }

        // 删除博客
        blogDao.deleteBlog(blogId);
        resp.sendRedirect("blog_list.html");
    }
}
